package main

import (
	"fmt"
	"log"
	"net/http"
	"time"

	"github.com/hashicorp/consul/api"
)

func main() {
	// 创建Consul客户端
	config := api.DefaultConfig()
	config.Address = "localhost:8500"
	client, err := api.NewClient(config)
	if err != nil {
		log.Fatal(err)
	}

	// 创建HTTP服务
	server := &http.Server{
		Addr:    ":8080",
		Handler: http.HandlerFunc(healthHandler),
	}

	// 注册服务到Consul
	registration := new(api.AgentServiceRegistration)
	registration.Name = "my-service"
	registration.ID = "my-service-1"
	registration.Address = "localhost"
	registration.Port = 8080
	registration.Check = &api.AgentServiceCheck{
		HTTP:     "http://localhost:8080/health",
		Interval: "10s",
		Timeout:  "1s",
	}
	err = client.Agent().ServiceRegister(registration)
	if err != nil {
		log.Fatal(err)
	}

	// 启动HTTP服务
	log.Println("Starting HTTP server...")
	err = server.ListenAndServe()
	if err != nil {
		log.Fatal(err)
	}
}

func healthHandler(w http.ResponseWriter, r *http.Request) {
	// 健康检查处理程序
	w.WriteHeader(http.StatusOK)
	w.Write([]byte(fmt.Sprintf("OK (timestamp: %d)", time.Now().Unix())))
}
